package com.loe.view;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.res.TypedArray;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.AttributeSet;
import android.widget.ImageView;

/**
 * 比例image
 */
@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@SuppressLint("AppCompatCustomView")
public class XImageView extends RoundImageView
{
    public XImageView(Context context)
    {
        this(context, null);
    }

    public XImageView(Context context, AttributeSet attrs)
    {
        this(context, attrs, 0);
        init(context, attrs);
    }

    public XImageView(Context context, AttributeSet attrs, int defStyleAttr)
    {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    private float rate = -1f;
    private boolean isAuto = false;

    private void init(Context context, AttributeSet attrs)
    {
        TypedArray array = context.obtainStyledAttributes(attrs, R.styleable.XImageView);
        rate = array.getFloat(R.styleable.XImageView_image_rate, rate);
        isAuto = array.getBoolean(R.styleable.XImageView_image_isAuto, isAuto);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        if (getDrawable() == null)
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            return;
        }
        // 计算出ImageView的宽度
        int viewWidth = MeasureSpec.getSize(widthMeasureSpec);
        if(isAuto)
        {
            // 根据图片长宽比例算出ImageView的高度
            int viewHeight = viewWidth * getDrawable().getIntrinsicHeight() / getDrawable()
                    .getIntrinsicWidth();
            // 将计算出的宽度和高度设置为图片显示的大小
            setMeasuredDimension(viewWidth, viewHeight);
        }else if(rate > 0)
        {
            // 将计算出的宽度和高度设置为图片显示的大小
            setMeasuredDimension(viewWidth, (int) (viewWidth * rate));
        }else
        {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        }
    }
}
